<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Login;
use App\Models\Role;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Mews\Captcha\Facades\Captcha;
use IP2City;


/**
 * 登录相关
 * Class CateController
 * @package App\Http\Controllers
 */
class AuthController extends Controller {


    public function login(Request $request){
        $data = $request->all();
//        //判断用户是否存在
//        $user = Users::where('openid',$credentials['username'])->where('is_admin',Users::ADMIN_1)->first();
//        if(!$user || strlen($credentials['username'])>15){
//            return $this->returnJson(1,'管理员账户不存在');
//        }
        $credentials = [
            'username' => $data['username'],
            'password' => $data['password'],
        ];
        $token = auth('admin')->attempt($credentials);
        if ($token) {
            $user = auth('admin')->user();
            //106.85.218.84
            $ip = $request->ip();

//            //TODO 上线必须换成真实的IP地址
            if (config('app.env') == 'production') {
                $address = IP2City::ip2addr('106.85.218.84');
                $address = trim(implode('-',$address),'-');
            }
            //登录日志
            $login_log = [
                'username' => $user['username'],
                'nickname' => $user['nickname'],
                'admin_id' => $user['id'],
                'ip' => $ip,
                'address' => $address ?? '',
                'login_at' => Carbon::now()
            ];
            Login::create($login_log);
            //查询角色权限
            $role = Role::findOrFail($user['role_id']);
            $login = [
                'user' => ['username' => $user['nickname'],'role_id' => $user['role_id'],'role_rules' => $role['access_ids']],
                'access_token' => $token,
                'token_type' => 'bearer',
                'expires_in' => auth('admin')->factory()->getTTL() * 60
            ];
            return $this->writeJson(0,$login,'登录成功，页面即将跳转...');
        }

//        $user->update(['login_at'=>Carbon::now()]);
        return $this->writeJson(1,null,'账户或者密码错误');
    }

//
//
//    public function refresh(Request $request){
//        try {
//            $refreshToken = $request->get('refresh_token','');
//            if(empty($refreshToken)){
//                return $this->returnJson(1, '参数错误');
//            }
//            $client = new Client();
//            $url = request()->root() . '/oauth/token';
//            $params = array_merge(config('passport.refresh'), [
//                'refresh_token' => $refreshToken,
//            ]);
//            $response = $client->request('POST', $url, ['form_params' => $params]);
//            $token_info = json_decode($response->getBody()->getContents());
//            return $this->writeJson(0,'',$token_info);
//        } catch (\Exception $e) {
//            return $this->writeJson(1, '刷新失败');
//        }
//    }
//
//    public function logout(){
//        try {
//            if (auth()->guard('api')->check()) {
//                auth()->guard('api')->user()->token()->delete();
//                return $this->returnJson(0,'登出成功,页面即将跳转...');
//            }
//        } catch (\Exception $e) {
//            return $this->writeJson(1, '网络超时，请刷新再试');
//        }
//
//    }


    public function captcha(){
        $captcha = Captcha::create('default', true);
        return $this->writeJson(0,$captcha);
    }

    public function getPengZong(){
//        $client = new Client();
//        $url = request()->root() . '/oauth/token';
//        $params = array_merge(config('passport.proxy'), [
//            'username' => $credentials['username'],
//            'password' => $credentials['password'],
//        ]);
//        $response = $client->request('POST', $url, ['form_params' => $params]);
//        $token_info = json_decode($response->getBody()->getContents());
    }

}
